package com.hk.core.web.mvc;

import com.hk.commons.query.OrderUtils;
import com.hk.commons.query.QueryModel;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.lang.reflect.Type;
import java.util.List;

/**
 * 对前端请求的order进行筛选过滤
 * <p>
 * 如果使用 {@link Bean} 的注解方式注入的Bean,要加上 {@link  org.springframework.web.bind.annotation.ControllerAdvice} 注解
 * 如果使用 {@link  RequestMappingHandlerAdapter#setRequestBodyAdvice(List)} 可以不使用这个注解
 *
 * @author Kevin
 * @date 2024-03-23 16:02
 */
//@ControllerAdvice
public class QueryModelRequestBodyAdvice extends RequestBodyAdviceAdapter {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return QueryModel.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
                                MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (body instanceof QueryModel<?> queryModel) {
            queryModel.addOrders(OrderUtils.escapeFilter(queryModel.getOrders()));
        }
        return body;
    }
}
